package com.mcppro.aidatabase.repository;

import com.mcppro.aidatabase.entity.ChatLog;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 聊天日志数据访问层
 * 
 * @author MCP Pro
 */
@Repository
public interface ChatLogRepository extends JpaRepository<ChatLog, Long> {

    /**
     * 根据会话ID查找聊天记录
     */
    List<ChatLog> findBySessionIdOrderByCreatedAtAsc(String sessionId);

    /**
     * 根据执行状态查找聊天记录
     */
    List<ChatLog> findByExecutionStatus(ChatLog.ExecutionStatus status);

    /**
     * 查找指定时间范围内的聊天记录
     */
    List<ChatLog> findByCreatedAtBetween(LocalDateTime startTime, LocalDateTime endTime);

    /**
     * 根据会话ID删除聊天记录
     */
    void deleteBySessionId(String sessionId);

    /**
     * 统计各状态的记录数量
     */
    @Query("SELECT c.executionStatus, COUNT(c) FROM ChatLog c GROUP BY c.executionStatus")
    List<Object[]> countByExecutionStatus();

    /**
     * 查找最近的聊天记录
     */
    @Query("SELECT c FROM ChatLog c ORDER BY c.createdAt DESC")
    List<ChatLog> findRecentChatLogs(@Param("limit") int limit);

    /**
     * 统计平均执行时间
     */
    @Query("SELECT AVG(c.executionTimeMs) FROM ChatLog c WHERE c.executionStatus = 'SUCCESS'")
    Double getAverageExecutionTime();
}